﻿using System;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;


namespace DPMQWindowsService
{




    public static class MQRPServer
    {






        public static bool Subscribe = true;
        private static readonly object lockHelper = new object();









        public static bool Producer(string value)
        {

            string curi = System.Configuration.ConfigurationManager.AppSettings["uri"].ToString();
            string mquser = System.Configuration.ConfigurationManager.AppSettings["mquser"].ToString();
            string mqpass = System.Configuration.ConfigurationManager.AppSettings["mqpass"].ToString();

            bool success = false;

            try
            {
                var qName = "SZHDP.directqueue";
                var exchangeName = "SZHDP.directqueue";
                //var exchangeType = "Direct";//topic、fanout,Direct
                var routingKey = "routekey";
                var uri = new Uri(curi);
                //var uri = new Uri("host=127.0.0.1;virtualhost=/;");
                var factory = new ConnectionFactory
                {                   
                    UserName = mquser,
                    Password = mqpass,
                    RequestedHeartbeat = 0,
                    VirtualHost = "/",
                    Endpoint = new AmqpTcpEndpoint(uri)
                };
                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {

                        //设置交换器的类型  名字 ,类型 ,持久化,自动删除
                        channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, true, false);

                        //声明一个队列，设置队列是否持久化，排他性独占，与自动删除
                        channel.QueueDeclare(qName, true, false, false, null);

                        //绑定消息队列，交换器，routingkey
                        channel.QueueBind(qName, exchangeName, routingKey);
                        var properties = channel.CreateBasicProperties();
                        //队列持久化
                        properties.Persistent = true;


                        //var m = "abcdefg1234567";
                        //string sSQL = "select top 1 data from API_SetDataTest order by CreateTime desc ";
                        //var rst = Src.connMetalLDB.Query(sSQL);
                        //var jar = rst.Tables[0].Rows[0][0].ToString();

                        var body = Encoding.UTF8.GetBytes(value);


                        try
                        {

                            //channel.TxSelect();
                            channel.ConfirmSelect();
                            //发送信息
                            channel.BasicPublish(exchangeName, routingKey, properties, body);
                            success = channel.WaitForConfirms(new TimeSpan(0, 0, 10));
                            if (success)
                            {
                                return success;
                            }

                            //channel.TxCommit();
                        }
                        catch
                        {
                            //channel.TxRollback();
                            return success;
                        }

                    }
                }






                return success;




            }
            catch (Exception ex)
            {
                LogWriter.Instance.writeError(ex.ToString());
                return success;
            }
        }















        public static void Consumer()
        {
            try
            {
                string curi = System.Configuration.ConfigurationManager.AppSettings["uri"].ToString();
                string mquser = System.Configuration.ConfigurationManager.AppSettings["mquser"].ToString();
                string mqpass = System.Configuration.ConfigurationManager.AppSettings["mqpass"].ToString();

                Subscribe = true;

                //http://www.manew.com/thread-103751-1-1.html
                var qName = "SZHDP.directqueue";
                var exchangeName = "SZHDP.directqueue";
                //var exchangeType = "Direct";//topic、fanout,Direct
                var routingKey = "routekey";

               
                var uri = new Uri(curi);


                var factory = new ConnectionFactory
                {
                  
                    UserName = mquser,
                    Password = mqpass,
                  
                    RequestedHeartbeat = 0,
                    VirtualHost = "/",
                    Endpoint = new AmqpTcpEndpoint(uri)
                };
                using (var connection = factory.CreateConnection())
                {
                    using (var channel = connection.CreateModel())
                    {
                        channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, true, false);
                        channel.QueueDeclare(qName, true, false, false, null);
                        channel.QueueBind(qName, exchangeName, routingKey);

                        channel.BasicQos(0, 1, false);

                        ////定义这个队列的消费者
                        QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel);


                        //false为手动应答，true为自动应答
                        channel.BasicConsume(qName, false, consumer);


                        while (Subscribe)
                        {

                            lock (lockHelper)
                            {
                                BasicDeliverEventArgs ea;
                                bool isMQ = consumer.Queue.Dequeue(1500, out ea);
                                //string SqlErr = "";
                                try
                                {
                                    if (isMQ)
                                    {
                                        byte[] bytes = ea.Body;
                                        var messageStr = Encoding.UTF8.GetString(bytes);

                                        var msg1 = messageStr.Split(';')[0];
                                        var inserttype = messageStr.Split(';')[1];//insert type processdata or alarm
                                        var msg2 = messageStr.Split(';')[2];
                                        var msg3 = messageStr.Split(';')[3];

                                        var Category = msg2;
                                        switch (Category)
                                        {
                                            case "POC":


                                                string sSQL = "";
                                                string guid = Guid.NewGuid().ToString("N");
                                                if (inserttype.ToLower() == "processdata")
                                                {
                                                    Models.SinglePOCProcessData immdata = JsonConvert.DeserializeObject<Models.SinglePOCProcessData>(msg1);
                                                    Models.MachineProcessDataHead head = new Models.MachineProcessDataHead();
                                                    head.GUID = Guid.NewGuid().ToString("N");
                                                    head.uploadIP = immdata.ip;
                                                    head.uploadupdateDt = immdata.updateDt;
                                                    head.MachineName = msg3.Split(',')[0];
                                                    head.ip = msg3.Split(',')[1];
                                                    head.DataString = msg1;
                                                    head.Category = Category;
                                                    head.CreateTime = DateTime.Now;


                                                  //  SqlErr = "insert into [API_ErrMessageLog] ([GUID],[MachineName],[ip],[CreateTime],[DataString],"
                                                  //+ "[uploadIP],[uploadupdateDt]) values  ('"
                                                  //    + guid + "','" + head.MachineName + "', '" + head.ip + "','" + head.CreateTime + "','"
                                                  //    + head.CreateTime + "','" + msg1 + "'  ) ; ";

                                                    sSQL = "insert into [API_MachineProcessDataHead] ([GUID],[MachineName],[ip],[Category],[CreateTime],[DataString],"
                                                    + "[uploadIP],[uploadupdateDt]) values  ('"
                                                            + guid + "','" + head.MachineName + "', '" + head.ip + "','"
                                                            + Category + "','" + head.CreateTime + "','"
                                                            + msg1 + "','" + head.uploadIP + "', '" + head.uploadupdateDt + "' ) ; ";

                                                    var mdetail = immdata._parm;
                                                    sSQL += "insert into [API_MachineProcessDataDetail] ([GUID],[ipaddr],[event_time],[actCloseTime],[actTimFill1],"
                                                    + "[actTimPlst1],[actTimCyc],[actStrCsh1],[actPrsMachSpecMax],[actTmpBrlZn1],[actTmpBrlZn3],[actTmpBrlZn4],"
                                                    + "[actTmpBrlZn5],[actTmpBrlZn8],[_count],[actPrsXfrSpec1],[actCntCyc],[actStsMach],"
                                                    + "[Set_SB_UpperLimitOfNozzle1Temperature],[Set_SB_UpperLimitOfBarrel1Temperature],"
                                                    + "[Set_SB_UpperLimitOfBarrel2Temperature],[Set_SB_UpperLimitOfBarrel3Temperature],[Set_SB_UpperLimitOfBarrel4Temperature],"
                                                    + "[Set_SB_UpperLimitOfFeedThroatTemperature],[Set_SB_LowerLimitOfNozzle1Temperature],[Set_SB_LowerLimitOfBarrel1Temperature],"
                                                    + "[Set_SB_LowerLimitOfBarrel2Temperature],[Set_SB_LowerLimitOfBarrel3Temperature],[Set_SB_LowerLimitOfBarrel4Temperature],"
                                                    + "[Set_SB_LowerLimitOfFeedThroatTemperature],"
                                                    + "[Set_SB_Nozzle1Temperature],[Set_SB_Barrel1Temperature],[Set_SB_Barrel2Temperature],[Set_SB_Barrel3Temperature],"
                                                    + "[Set_SB_FeedThroatTemperature],[alarmCode],[alarmDescEn],[alarmDescCN]) values  ('"
                                                    + guid + "','" + mdetail.ipaddr + "', '" + mdetail.event_time + "','" + mdetail.actCloseTime + "','" + mdetail.actTimFill1 + "','"
                                                    + mdetail.actTimPlst1 + "','" + mdetail.actTimCyc + "','" + mdetail.actStrCsh1 + "','" + mdetail.actPrsMachSpecMax + "','"
                                                    + mdetail.actTmpBrlZn1 + "','" + mdetail.actTmpBrlZn3 + "','" + mdetail.actTmpBrlZn4 + "','" + mdetail.actTmpBrlZn5 + "','"
                                                    + mdetail.actTmpBrlZn8 + "','" + mdetail._count + "','" + mdetail.actPrsXfrSpec1 + "','" + mdetail.actCntCyc + "','" + mdetail.actStsMach + "','"

                                                    + mdetail.Set_SB_UpperLimitOfNozzle1Temperature + "','" + mdetail.Set_SB_UpperLimitOfBarrel1Temperature + "','"
                                                    + mdetail.Set_SB_UpperLimitOfBarrel2Temperature + "','" + mdetail.Set_SB_UpperLimitOfBarrel3Temperature + "','" + mdetail.Set_SB_UpperLimitOfBarrel4Temperature + "','"
                                                    + mdetail.Set_SB_UpperLimitOfFeedThroatTemperature + "','" + mdetail.Set_SB_LowerLimitOfNozzle1Temperature + "','" + mdetail.Set_SB_LowerLimitOfBarrel1Temperature + "','"
                                                    + mdetail.Set_SB_LowerLimitOfBarrel2Temperature + "','" + mdetail.Set_SB_LowerLimitOfBarrel3Temperature + "','" + mdetail.Set_SB_LowerLimitOfBarrel4Temperature + "','"
                                                    + mdetail.Set_SB_LowerLimitOfFeedThroatTemperature + "','"
                                                    + mdetail.Set_SB_Nozzle1Temperature + "','" + mdetail.Set_SB_Barrel1Temperature + "','" + mdetail.Set_SB_Barrel2Temperature + "','" + mdetail.Set_SB_Barrel3Temperature + "','"
                                                    + mdetail.Set_SB_FeedThroatTemperature + "','" + mdetail.alarmCode + "','" + mdetail.alarmDescEn + "','" + mdetail.alarmDescCN + "' ) ; ";




                                                }
                                                else if (inserttype.ToLower() == "alarm")
                                                {

                                                    Models.SinglePOCProcessDataAlarm immdata = JsonConvert.DeserializeObject<Models.SinglePOCProcessDataAlarm>(msg1);
                                                    Models.MachineProcessDataHead head = new Models.MachineProcessDataHead();
                                                    head.GUID = Guid.NewGuid().ToString("N");
                                                    head.uploadIP = immdata.ip;
                                                    head.uploadupdateDt = immdata.updateDt;
                                                    head.MachineName = msg3.Split(',')[0];
                                                    head.ip = msg3.Split(',')[1];
                                                    head.DataString = msg1;
                                                    head.Category = Category;
                                                    head.CreateTime = DateTime.Now;


                                                  //  SqlErr = "insert into [API_ErrMessageLog] ([GUID],[MachineName],[ip],[CreateTime],[DataString],"
                                                  //+ "[uploadIP],[uploadupdateDt]) values  ('"
                                                  //    + guid + "','" + head.MachineName + "', '" + head.ip + "','" + head.CreateTime + "','"
                                                  //    + head.CreateTime + "','" + msg1 + "'  ) ; ";

                                                    sSQL = "insert into [API_MachineProcessDataHead] ([GUID],[MachineName],[ip],[Category],[CreateTime],[DataString],"
                                                    + "[uploadIP],[uploadupdateDt]) values  ('"
                                                            + guid + "','" + head.MachineName + "', '" + head.ip + "','"
                                                            + Category + "','" + head.CreateTime + "','"
                                                            + msg1 + "','" + head.uploadIP + "', '" + head.uploadupdateDt + "' ) ; ";

                                                    var mdetail = immdata._parm;
                                                    for (int i = 0; i <= mdetail.alarm_list.Count - 1; i++)
                                                    {
                                                        sSQL += "insert into [API_MachineProcessDataDetail] ([GUID],[ipaddr],[event_time],[actCloseTime],[actTimFill1],"
                                                 + "[actTimPlst1],[actTimCyc],[actStrCsh1],[actPrsMachSpecMax],[actTmpBrlZn1],[actTmpBrlZn3],[actTmpBrlZn4],"
                                                 + "[actTmpBrlZn5],[actTmpBrlZn8],[_count],[actPrsXfrSpec1],[actCntCyc],[actStsMach],"
                                                 + "[Set_SB_UpperLimitOfNozzle1Temperature],[Set_SB_UpperLimitOfBarrel1Temperature],"
                                                 + "[Set_SB_UpperLimitOfBarrel2Temperature],[Set_SB_UpperLimitOfBarrel3Temperature],[Set_SB_UpperLimitOfBarrel4Temperature],"
                                                 + "[Set_SB_UpperLimitOfFeedThroatTemperature],[Set_SB_LowerLimitOfNozzle1Temperature],[Set_SB_LowerLimitOfBarrel1Temperature],"
                                                 + "[Set_SB_LowerLimitOfBarrel2Temperature],[Set_SB_LowerLimitOfBarrel3Temperature],[Set_SB_LowerLimitOfBarrel4Temperature],"
                                                 + "[Set_SB_LowerLimitOfFeedThroatTemperature],"
                                                 + "[Set_SB_Nozzle1Temperature],[Set_SB_Barrel1Temperature],[Set_SB_Barrel2Temperature],[Set_SB_Barrel3Temperature],"
                                                 + "[Set_SB_FeedThroatTemperature],[alarmCode],[alarmDescEn],[alarmDescCN]) values  ('"
                                                 + guid + "','" + mdetail.ipaddr + "', '" + mdetail.alarm_list[i].event_time + "','" + mdetail.actCloseTime + "','" + mdetail.actTimFill1 + "','"
                                                 + mdetail.actTimPlst1 + "','" + mdetail.actTimCyc + "','" + mdetail.actStrCsh1 + "','" + mdetail.actPrsMachSpecMax + "','"
                                                 + mdetail.actTmpBrlZn1 + "','" + mdetail.actTmpBrlZn3 + "','" + mdetail.actTmpBrlZn4 + "','" + mdetail.actTmpBrlZn5 + "','"
                                                 + mdetail.actTmpBrlZn8 + "','" + mdetail._count + "','" + mdetail.actPrsXfrSpec1 + "','" + mdetail.actCntCyc + "','" + mdetail.actStsMach + "','"

                                                 + mdetail.Set_SB_UpperLimitOfNozzle1Temperature + "','" + mdetail.Set_SB_UpperLimitOfBarrel1Temperature + "','"
                                                 + mdetail.Set_SB_UpperLimitOfBarrel2Temperature + "','" + mdetail.Set_SB_UpperLimitOfBarrel3Temperature + "','" + mdetail.Set_SB_UpperLimitOfBarrel4Temperature + "','"
                                                 + mdetail.Set_SB_UpperLimitOfFeedThroatTemperature + "','" + mdetail.Set_SB_LowerLimitOfNozzle1Temperature + "','" + mdetail.Set_SB_LowerLimitOfBarrel1Temperature + "','"
                                                 + mdetail.Set_SB_LowerLimitOfBarrel2Temperature + "','" + mdetail.Set_SB_LowerLimitOfBarrel3Temperature + "','" + mdetail.Set_SB_LowerLimitOfBarrel4Temperature + "','"
                                                 + mdetail.Set_SB_LowerLimitOfFeedThroatTemperature + "','"
                                                 + mdetail.Set_SB_Nozzle1Temperature + "','" + mdetail.Set_SB_Barrel1Temperature + "','" + mdetail.Set_SB_Barrel2Temperature + "','" + mdetail.Set_SB_Barrel3Temperature + "','"
                                                 + mdetail.Set_SB_FeedThroatTemperature + "','" + mdetail.alarm_list[i].alm_code + "','" + mdetail.alarm_list[i].alm_code_desc_en + "','" + mdetail.alarm_list[i].alm_code_desc_cn + "' ) ; ";

                                                    }




                                                }

                                                var result = Src.connMetalLDB.Insert(sSQL);

                                                if (result != 1)
                                                {
                                                    //result = Src.connMetalLDB.Insert(SqlErr);
                                                }
                                                ////处理消息
                                                channel.BasicAck(ea.DeliveryTag, false);
                                                break;
                                            default:
                                                break;
                                        }

                                        //Console.WriteLine("Receive a Message, DateTime:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Title:OKOKLA");

                                    }


                                }
                                catch (Exception ex)
                                {
                                    if (ea != null)
                                    {
                                        //////处理消息
                                        ////channel.BasicAck(ea.DeliveryTag, false);
                                        //if (SqlErr != "")
                                        //{
                                        //    int iee = Src.connMetalLDB.Insert(SqlErr);
                                        //}

                                    }
                                    LogWriter.Instance.writeError(ex.ToString());
                                    continue;
                                }
                            }


                        }


                    }
                }


            }
            catch (Exception ex)
            {
                
                Subscribe = false;
                LogWriter.Instance.writeError(ex.ToString());
            }
        }










    }









}
